from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, login
from django.http import HttpResponse
from django.shortcuts import render
from .models import EnvironmentData, CardData
from django.contrib.auth.models import User

import json
from django.http import JsonResponse
from djangoProject.mqtt import client as mqtt_client

def login_view(request):
    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')
        user = authenticate(request, username=username, password=password)
        if user is not None:
            login(request, user)
            return redirect('dashboard')
        else:
            return render(request, 'back/login.html', {'error': 'Invalid credentials'})
    return render(request, 'back/login.html')




def register_view(request):
    if request.method == 'POST':
        username = request.POST.get('username')
        password1 = request.POST.get('password1')
        password2 = request.POST.get('password2')
        
        if password1 != password2:
            return render(request, 'back/register.html', {'error': '密码不匹配'})
        
        # 检查用户名是否已存在
        if User.objects.filter(username=username).exists():
            return render(request, 'back/register.html', {'error': '用户名已存在'})
        
        # 创建用户
        user = User.objects.create_user(username=username, password=password1)
        
        # 自动登录用户
        user = authenticate(username=username, password=password1)
        login(request, user)
        
        # 注册成功后重定向到仪表盘页面，这里假设仪表盘的 URL 名称为 'dashboard'
        return redirect('login')
    
    return render(request, 'back/register.html')

#


def dashboard_view(request):
    if not request.user.is_authenticated:
        return redirect('login')
    environment_data = EnvironmentData.objects.all()
    card_data = CardData.objects.all()
    return render(request, 'back/dashboard.html', {
        'environment_data': environment_data,
        'card_data': card_data,
    })


# def write_card(request):
#     if request.method == 'POST':
#         card_number = request.POST.get('card_number')
#         information = request.POST.get('information')

#         # 准备数据为 JSON
#         data = {
#             'card_number': card_number,
#             'information': information
#         }
#         payload = json.dumps(data)

#         # 发布到 MQTT 主题
#         try:
#             # 发布到 MQTT 主题
#             publish_message(request, topic='/writecard', msg=payload)

#             # 保存到数据库
#             CardData.objects.create(card_number=card_number, information=information)
#             return HttpResponse('数据成功发送至 MQTT 主题 /writecard!')
        
#         except Exception as e:
#             return HttpResponse(f'无法发布数据到 MQTT: {str(e)}')

#         return redirect('dashboard')

#     return render(request, 'back/write_card.html')
# 修正 publish_message 函数定义
def publish_message(request):
    try:
        request_data = json.loads(request.body)
        topic = request_data.get('topic')
        msg = request_data.get('msg')
        rc, mid = mqtt_client.publish(topic, msg)
        return JsonResponse({'code': rc})
    except Exception as e:
        return JsonResponse({'error': str(e)}, status=500)

def publish_message1(request, topic, msg):
    try:
        rc, mid = mqtt_client.publish(topic, msg)
        return JsonResponse({'code': rc})
    except Exception as e:
        return JsonResponse({'error': str(e)}, status=500)
    
# 更新 write_card 视图函数
def write_card(request):
    if request.method == 'POST':
        card_number = request.POST.get('card_number')
        information = request.POST.get('information')
        data = {'card_number': card_number, 'information': information}
        payload = json.dumps(data)

        try:
            # 发布到 MQTT 主题
            publish_message1(request, topic='/writecard', msg=payload)

            # 保存到数据库
            CardData.objects.create(card_number=card_number, information=information)
            return HttpResponse('数据成功发送至 MQTT 主题 /writecard!')

        except Exception as e:
            return HttpResponse(f'无法发布数据到 MQTT: {str(e)}')

        return redirect('dashboard')

    return render(request, 'back/write_card.html')

def read_card(request):
    if not request.user.is_authenticated:
        return redirect('login')

    latest_environment_data = EnvironmentData.objects.all()
    print(latest_environment_data)
    # print(animals)

    return render(request, 'back/dashboard.html', {
        'environment_data': latest_environment_data,
    })

def send_mqtt_message(request):
    if request.method == 'POST':
        request_data = json.loads(request.body)
        topic = request_data.get('topic')
        message = request_data.get('message')
        mqtt_client.publish(topic, message)
        return JsonResponse({'status': 'success'})
    return JsonResponse({'status': 'failed'}, status=400)